/**
 * js 配置/工具集合
 * Created by Zachary on 2017/7/11.
 */
var gtr = (function ($) {
    //region 版本说明
    var version={
        v:"1.1.7",
        author:""
    }
    //endregion
    //region  基础配置
    var config = {
       debugger:false,
       wechatAuthor:"https://www.yuelinshe.com/vizcaya/wechat/first?returnUrl="+encodeURIComponent(window.location.href),
       baseUrl:"https://www.yuelinshe.com/vizcaya/",//悦邻舍
       locallurl:"https://www.yuelinshe.com/vizcayafont/",
       // wechatLocalUrl:"https://asp.guangkee.com/wechatd/",
       imgShowUrl:"https://yuelinshe-1253333391.costj.myqcloud.com/",
       bucket : 'yuelinshe',
       appid : 1253333391,
       sid : "AKIDFQTPEwb6VyUvGSwREtdLxeDeyAYsD84t",
       skey : "qZ6Xq150nSzQjvzvlS1SlvxumV3UpEXg",
       region : 'tj',
       myFolder : '/vizcaya/',
    };
    //endregion

    //region url处理相关
    var url = {
        wechatFormat:function(url){
            if(url.indexOf("http")!=-1){
                return url;
            }
            if(url){
                return config.wechatLocalUrl + url;
            }else{
                return config.wechatLocalUrl;
            }
        },
        format: function(url) {//接口路径
            if(url.indexOf("http")!=-1){
                return url;
            }
            if(url){
                return config.baseUrl + url;
            }else{
                return config.baseUrl;
            }

        },
        imgFormat:function(url,width,height,itype){
            if(!url){
                //默认图片处理
                if(!itype){
                    return "http://files.yetong.org/web/default_guide.png";
                }
                switch(itype){
                    case 0:
                        return "http://files.yetong.org/web/default_guide.png";
                    case 1:
                        return "http://files.yetong.org/web/default_shop.png";
                    default:
                        return "http://files.yetong.org/web/default_guide.png";
                }
            }
            if(url.indexOf("http")!=-1){
                url=url.indexOf("?")==-1?(url+"?"):url;
                if(width&&height){
                    url=url+"imageView2/2/w/"+width+"/h/"+height;
                    return url;
                }
                if(width){
                    url=url+"imageView2/2/w/"+width;
                    return url;
                }
                if(height){
                    url=url+"imageView2/2/h/"+height;
                    return url;
                }
                return url;
            }
            var baseUrl=config.imgShowUrl +url+"?";
            if(width&&height){
                baseUrl=baseUrl+"imageView2/2/w/"+width+"/h/"+height;
                return baseUrl;
            }
            if(width){
                baseUrl=baseUrl+"imageView2/2/w/"+width;
                return baseUrl;
            }
            if(height){
                baseUrl=baseUrl+"imageView2/2/h/"+height;
                return baseUrl;
            }
            return baseUrl;
        },
        urlHref:function (url) {//跳转路径

            if(url) {
                if(url.indexOf("&v")!=-1||url.indexOf("?v")!=-1){
                    return config.locallurl+url;
                }
                url=(url.indexOf("?")!=-1)?(url+"&v="+version.v):(url+"?v="+version.v);
                return config.locallurl+url;
            }else{
                return config.locallurl;
            }
        }
    };
    //endregion

    //region 等待框,弹出框alert,确认框confirm
    var moadl = {
        waiting: function (opts) {
            var defaultOpts = {
                title: "请等待……",
                icon:""
            }
            var setting = $.extend({}, defaultOpts, opts);
            this.opt=setting;
            var plugin = this;
            plugin.createWaitHtml(setting);
            if(!setting.wait){
                setTimeout(function(){
                    $(".msg-modal").fadeOut("slow","swing",function () {
                        $(".msg-modal").remove();
                        if(!plugin.opt.closeDiv){
                            return false;
                        }
                        plugin.opt.closeDiv();
                    });
                },1000);
            }
        },
        tip: function (opts) {
            var defaultOpts = {
                title: "发生错误",
            }
            var setting = $.extend({}, defaultOpts, opts);
            this.opt = setting;
            var plugin = this;
            plugin.createTipHtml(setting);
            setTimeout(function(){
              $(".msg-modal-tip-content").removeClass("show");
            },1900)
            setTimeout(function(){
                $(".msg-modal").fadeOut("slow","swing",function () {
                    $(".msg-modal").remove();
                });
            },2500); 
        },
        alert:function(opts){
            var defaultOpts = {
                title:'错误提示',
                content:'出错了',
                submitName:'确定'
            }
            var setting = $.extend({}, defaultOpts, opts);
            this.opt=setting;
            var plugin = this;
            plugin.createHtml('Alert');
            $(".msg-modal").find(".btnOk").on("click",function () {
                plugin.submitCallBack();
            });
            $(".msg-modal").find(".close").on("click",function () {
                plugin.closeDiv();
            });
        },
        confirm:function(opts){
            var defaultOpts = {
                title:'提示',
                content:'出错了',
                submitName:'确定',
                refuseName:'取消'
            }
            var setting = $.extend({}, defaultOpts, opts);
            this.opt=setting;
            var plugin = this;
            plugin.createHtml('Confirm');
            $(".msg-modal").find(".close").on("click",function () {
                plugin.closeDiv();
            });
            $(".msg-modal").find(".btnOk").on("click",function () {
                plugin.submitCallBack();
            });
            $(".msg-modal").find(".btnNo").on("click",function () {
                plugin.closeCallBack();
            });
        },
        createHtml:function (type) {
            var _foothtml='';
            switch (type){
                case "Alert":
                    _foothtml='<div class="msg-modal-btn btnOk">'+this.opt.submitName+'</div>';
                    break;
                case "Confirm":
                    _foothtml = '<div class="msg-modal-btn btnNo">'+this.opt.refuseName+'</div>';
                    _foothtml += '<div class="msg-modal-btn btnOk">'+this.opt.submitName+'</div>';
                    break;
                default:
                    _foothtml='<div class="msg-modal-btn btnOk">'+this.opt.submitName+'</div>';
                    break;
            }
            var _html = "";
            _html += '<div class="msg-modal">';
            _html += '  <div class="msg-modal-mask"></div>';
            _html += '  <div class="msg-modal-content">';
            _html += '    <div class="title">'+this.opt.title+'';
            _html += '    </div>';
            _html += '    <div class="text">'+this.opt.content+'</div>';
            _html += '    <div class="foot">';
            _html +=_foothtml;
            _html += '    </div>';
            _html += '  </div>';
            _html += '</div>';
            $("body").append(_html);
        },
        createWaitHtml:function (setting) {
            var waitHtml ='<div class="msg-modal msg-modal-toast '+(setting.position || '')+'">' +
                '   <div class="msg-modal-toast-content">' +
                '     <span class="iconfont ' + setting.icon + '"></span>' +
                '     <p>' + setting.title + '</p>' +
                '   </div>'+
                '</div>';
            $("body").append(waitHtml);
        },
        createTipHtml:function (setting) {
            var tipHtml ='<div class="msg-modal msg-modal-tip">' +
                '   <div class="msg-modal-tip-content">'+setting.title+'</div>' +
                '</div>';
            $("body").append(tipHtml);
            setTimeout(function(){
               $(".msg-modal-tip-content").addClass("show");
            },0);
            
        },
        submitCallBack:function () {
            if(this.opt.submitCallBack){
                this.opt.submitCallBack();
            }
            $(".msg-modal").remove();
        },
        closeCallBack:function () {
            if(this.opt.closeCallBack){
                this.opt.closeCallBack();
            }
            $(".msg-modal").remove();
        },
        closeDiv:function () {
            if(this.opt.closeDiv){
                this.opt.closeDiv();
            }
            $(".msg-modal").remove();
        }
    }
    //endregion

    //region ajax 相关
    var ajax=function(opts){
        //备份opt中error和success方法
        var fn = {
            error: function (XMLHttpRequest, textStatus, errorThrown) { },
            success: function (data, textStatus) { }
        }
        if (opts.success) {
            fn.success = opts.success;
        }
         var token = storage.getToken();
        opts.cache = false;
        // opts.headers = $.extend({},{'token':token},opts.headers);
        //'eyJ1c2VySWQiOiI5MCIsImV4cGlyZSI6MjM2NDA4ODY1NDk0OSB9'
        opts.headers = $.extend({},{'Authorization':token},opts.headers);
        //扩展增强处理
        var _opt = $.extend(opts, {
            success: function (data, textStatus) {
                if(data.statusCode == 403){
                    modal.alert({
                        content:data.errorMsg
                    });
                }else{
                    fn.success(data, textStatus);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                var systemErrorPaneData = JSON.stringify({jqXHR:jqXHR,textStatus:textStatus,errorThrown:errorThrown});
               
            }

        });
        return $.ajax(_opt);
    }
    //endregion

    //region 日期相关
    Date.prototype.format=function (pattern) {
        if(!pattern){
            pattern = 'yyyy-MM-dd hh:mm:ss'; //默认形式
        }
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(pattern)) {
            pattern = pattern.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(pattern)) {
                pattern = pattern.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return pattern;
    }

    function getDateDiff(dateTimeStamp) {
      var minute = 1000 * 60;
      var hour = minute * 60;
      var day = hour * 24;
      var halfamonth = day * 15;
      var month = day * 30;
      var now = new Date().getTime();
      var diffValue = now - dateTimeStamp;
      if (diffValue < 0) { return; }
      var monthC = diffValue / month;
      var weekC = diffValue / (7 * day);
      var dayC = diffValue / day;
      var hourC = diffValue / hour;
      var minC = diffValue / minute;
      if (monthC >= 1) {
        result = "" + parseInt(monthC) + "月前";
      }
      else if (weekC >= 1) {
        result = "" + parseInt(weekC) + "周前";
      }
      else if (dayC >= 1) {
        result = "" + parseInt(dayC) + "天前";
      }
      else if (hourC >= 1) {
        result = "" + parseInt(hourC) + "小时前";
      }
      else if (minC >= 1) {
        result = "" + parseInt(minC) + "分钟前";
      } else
        result = "刚刚";
      return result;
    };

    String.prototype.FormatTimeDiff = function() {
      var timeStamp = (new Date(this)).getTime();
      return getDateDiff(timeStamp);
    };
    
    String.prototype.dateFormat=function (pattern) {
        return this.toDate().format(pattern);
    };
    Number.prototype.dateFormat=function(pattern){
        return this.toDate().format(pattern);
    };

    String.prototype.toDate=function(){
        return new Date(this);
    };
    Number.prototype.toDate=function(){
        return new Date(this);
    };
    var date={
        toDate:function(obj){
            //根据类型分别作转换
            //typeof obj =="String"
            //typeof obj =="String"
        }
    };
    //endregion

    //region 存储相关
    var storage={
        getToken:function(){
            //return  '2mdFOEP87TSly8KJWjPC+cccF6Erzfoj7b2uzfugGOi6kvtqs5Wm8cLlxkLpWFb8';
            return localStorage.getItem("token");
        },
        setToken:function(data){
            localStorage.setItem("token",data);
        },
        delToken:function(){
            localStorage.removeItem("token");
        },
        getUserInfo:function(){

        },
        setUserInfo:function(data){
            window.gkee.addLocalStorage("token",data);
        },
        delUserInfo:function(){
            window.gkee.dleLocalStorage("token");
        }
    }
    //endregion

    //region 参数相关
    var params={
        get:function(key){
            return this.getAll()[key];
        },
        getAll:function(){
            if (window.location.href.indexOf('?') == -1) {
                return false;
            }
            var vars = {}, hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                if(hashes[i]!=''){
                    hash = hashes[i].split('#')[0].split('=');
                    vars[hash[0]] = hash[1];
                }
            }
            return vars;
        }
    }
    //endregion

    //region 跳转，webview相关
    var win={
        open:function(url){
            window.location.href(url);
        },
        openNew:function(url,key){
            if(url.indexOf("http") == -1){
                url = config.locallurl+url;
            }
            if(!key){
                key = new Date().getTime().toString();
            };
            if(url.indexOf("&v") != -1 || url.indexOf("?v") != -1){
                window.gkee.createWebView(url,key);
                return;
            }
            url = url.indexOf("?") != -1?(url+"&v="+version.v):(url+"?v="+version.v);
            window.gkee.createWebView(url,key);
        },
        back:function () {
            window.history.go(-1);
        }
    };
    //endregion

    //region验证的一些方法
    var validate = {
        isPhone:function (phone) { //验证手机（首位为1的11位数字）
            if(!(/^[1][0-9]{10}$/.test(phone))){
                moadl.waiting({
                    title:'请输入正确的手机号',
                })
                return false;
            }
            return true;
        },
        checkJson:function(value){
            try{
                if(typeof value === 'object')
                    return true;
            }catch(e){
                return false;
            }
        },
        mobile:function(value){
            var MobileReGexp = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
            if(MobileReGexp.test(value)){
                return true;
            }
            return false;
        }
    }
    //endregion

    //region dom操作
    var dom = {
        bodyUnScroll:function(){
            $('body').on('touchmove',function(event){
                event.preventDefault();
            });
            $('body').css({'overflow':'hidden'});
        },
        bodyScroll:function(){
            $("body").off("touchmove");
            $('body').css({'overflow':'auto'});
        },
        scrollToTop:function(){
            $('body').scrollTop(0);
        }
    };
    //endregion


    //region一些常规的规范化
    var standard ={
        returnFloat : function(value){ //金额保持2位小数
            var value = Math.round(parseFloat(value)*100)/100;
            var xsd = value.toString().split(".");
            if(xsd.length == 1){
                value = value.toString()+".00";
                return value;
            }
            if(xsd.length > 1){
                if(xsd[1].length < 2){
                    value = value.toString() + "0";
                }
                return value;
            }
        }
    }
    //endregion
    return {
        version:version,
        config: config,
        url: url,
        modal:moadl,
        ajax:ajax,
        date:date,
        storage:storage,
        params:params,
        window:win,
        validate:validate,
        standard:standard,
        dom:dom,
        getDateDiff:getDateDiff
    }
})($);

if(!window.gkee){
    window.gkee = {};
}
window.g = gtr;


